// 登录验证、校验权限、登录重定向
import router from './router'
import store from './store'
import NProgress from 'nprogress' // Progress 进度条
import 'nprogress/nprogress.css' // Progress 进度条样式
import {
  Message
} from 'element-ui'
import {
  getToken,
  setToken,
  setUrl,
  setUser,
  setRole,
  getUrl
} from '@/utils/auth' // 验权
// const whiteList = ['/login'] // 不重定向白名单
router.beforeEach((to, from, next) => {
  console.log(getToken())
  NProgress.start()
  // cookie 没有token
  if (!getToken()) {
    const name = to.query.userName
    const token = to.query.token
    const url = to.query.url
    const userRole = to.query.userRole
    // console.log(getToken())
    if (token) { // cookie没有缓存 && 当前路由为默认进入路由
      setToken(token)
      setUser(name)
      setRole(userRole)
      setUrl(url)
      store.dispatch('GetInfo', url).then(res => {
        var fun = []
        var sys = []
        if (!fun) {
          fun = []
        }
        if (!sys) {
          sys = []
        }
        res.data.funList.forEach(item => {
          if (item.powerType === 'menu' && item.powerCode.indexOf('usercenter') > -1) {
            fun.push(item)
          }
        })
        console.log(fun)
        res.data.sysList.forEach(item => {
          if (item.powerType === 'menu' && item.powerCode.indexOf('usercenter') > -1) {
            sys.push(item)
          }
        })
        const power = fun.concat(sys)
        // 把携带权限所有信息传导store中
        store.dispatch('GenerateRoutes', power).then((res) => {
          router.addRoutes(res)
          next({ path: store.getters.redirect, replace: true })
        })
      }).catch((err) => {
        store.dispatch('FedLogOut').then(() => {
          Message.error(err || '请重新登录')
          next({
            path: '/'
          })
        })
      })
    } else { // cookie没有token && 当前路由不是默认
      // 没啥权限，滚!
      NProgress.done()
      window.location.replace(window.bossUrl.API_LOGIN)
    }
  } else { // cookie有缓存(应该不用判断是不是默认页,直接判断store.getter.roles)
    if (store.getters.roles && store.getters.roles.length > 0) {
      next()
    } else {
      const token = to.query.token
      const userRole = to.query.userRole
      const name = to.query.userName
      if (token) {
        setToken(token)
        setUser(name)
        setRole(userRole)
      }
      store.dispatch('GetInfo', getUrl()).then(response => {
        var fun = []
        var sys = []
        if (!fun) {
          fun = []
        }
        if (!sys) {
          sys = []
        }
        response.data.funList.forEach(item => {
          if (item.powerCode.indexOf('usercenter') > -1) {
            fun.push(item)
          }
        })
        response.data.sysList.forEach(item => {
          if (item.powerType === 'menu' && item.powerCode.indexOf('usercenter') > -1) {
            sys.push(item)
          }
        })
        const power = fun.concat(sys)
        if (Array.isArray(power) && power.length > 0) {
          store.dispatch('GenerateRoutes', power).then(res => {
            // 动态加载路由开始
            router.addRoutes(res)
            next({
              ...to,
              replace: true
            })
          })
        } else {
          // 没啥权限，滚!
          NProgress.done()
          window.location.replace(window.bossUrl.API_LOGIN)
        }
      })
    }
  }
  /*
   ******************
   * author: 马丰彦
   * date: 2019-07-04
   * function: 下方为上一版
   ******************
   */

  /* if (getToken()) {
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      if (store.getters.roles.length === 0) {
        store.dispatch('GetInfo').then(res => {
          console.log(res)
          // const roles = res.data.roles // roles must be a array !!
          var fun = res.data.funList
          var sys = res.data.sysList
          if (!fun) {
            fun = []
          }
          if (!sys) {
            sys = []
          }
          const power = fun.concat(sys)
          // 把携带权限所有信息传导store中
          store.dispatch('GenerateRoutes', power).then(() => {
            router.addRoutes(store.getters.addRouters)
            next({ ...to, replace: true })
          })
        }).catch((err) => {
          store.dispatch('FedLogOut').then(() => {
            Message.error(err || '请重新登录')
            next({ path: '/' })
          })
        })
      } else {
        next()
      }
    }
  } else {
    // 排除当前登录页
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`) // 否则全部重定向到登录页
      NProgress.done()
    }
  } */
})

router.afterEach(() => {
  NProgress.done() // 结束Progress
})
